package com.sltx.service.impl;

import com.sltx.dao.aaa.PackageMapper;
import com.sltx.dto.EntcolDTO;
import com.sltx.dto.aa;
import com.sltx.service.PackageService;
import com.sltx.util.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 分析对象维护
 */
@Service
public class PackageServiceImpl implements PackageService {

    @Value("${spring.datasource.aaa.jdbc-url}")
    private String url;
    //spring.datasource.aaa.driver-class-name=com.mysql.jdbc.Driver
    @Value("${spring.datasource.aaa.driver-class-name}")
    private String dd;
    @Value("${spring.datasource.aaa.username}")
    private String username;
    @Value("${spring.datasource.aaa.password}")
    private String password;

    Connection conn = null;
    Statement stmt = null;

    public PackageServiceImpl() {
    }

    @Autowired
    private PackageMapper packageMapper;

    @Override
    public Object insertExcel(List<Map<String, Object>> list, PageData pd) {
        try {
            //获取 spring.datasource.aaa.driver-class-name=com.mysql.jdbc.Driver
            Class.forName(dd);
            //url = jdbc:mysql://152.136.204.225:3306/sjs_product?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&useSSL=false
            //username = 数据库账号
            //password = 数据库密码
            conn = DriverManager.getConnection(url, username, password);
            //创建Connection对象传入false不会自动提交事务
            conn.setAutoCommit(false);
            //创建Statement对象来将SQL语句发送到数据库
            stmt = conn.createStatement();
            Date date = new Date();
            SimpleDateFormat dateTime = new SimpleDateFormat("yyyy-MM-dd");
            //随机生成一个uuid存储到数据库
            String uuid = UUID.randomUUID().toString();
            Map<String,Object> result = new HashMap<>();
            List<String> list1 = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                String uniscid = (String) list.get(i).get("统一社会信用代码");
                //判断表里面有没有此企业根据uniscid（统一社会信用代码）
                Integer count = packageMapper.getUniscidIsNo(uniscid);
                if (count <= 0) {
                    list1.add((String) list.get(i).get("企业名称"));
                    continue;
                }
                String sql = "insert into f_gqct_entcol(`qymd_id`, `entname`, `uniscid`) values ('" +
                        uuid + "','" +
                        list.get(i).get("企业名称") + "','" +
                        list.get(i).get("统一社会信用代码") + "');";
                System.out.println(sql);
                stmt.addBatch(sql);
                if (i % 100 == 0 && i != 0) {
                    stmt.executeBatch();
                    conn.commit();
                    stmt.clearBatch();
                }
            }
            stmt.executeBatch();
            conn.commit();
            stmt.clearBatch();
            close();

            pd.put("id", uuid);
            //根据uuid查询f_gqct_entcol（企业名单企业详细列表）
            List<Map<String, Object>> qyNUmCount = packageMapper.getCount(pd);
            //上传多少条数据
            pd.put("qynum", qyNUmCount.get(0).get("count"));
            //上传日期
            pd.put("tjdata", dateTime.format(date));
            //存储到企业名单列表中
            packageMapper.addPackage(pd);
            //返回存储表中的企业名称
            result.put("qymc", list1);
            //返回存储表中的uuid
            result.put("id", uuid);
            return result;
        } catch (Exception e) {
            return e.toString();
        }
    }

    @Override
    public int updateExcel(PageData pd) {
        return packageMapper.updateExcel(pd);
    }

    @Override
    public String deleteExcel(PageData pd) {
        int result1 = packageMapper.deleteExcel(pd);
        int result2 = packageMapper.deleteExcel2(pd);
        if (result1 > 0 && result2 > 0) {
            return "删除成功";
        }
        return "删除失败";
    }

    @Override
    public Map getPackage(PageData pd) {
        int pageSize = Integer.parseInt(pd.get("pageSize").toString());
        int pageNo = Integer.parseInt(pd.get("pageNo").toString());
        Integer startPage = ((pageSize * (pageNo - 1)));
        pd.put("startPage", startPage.toString());
        Map map = new HashMap();
        String m = packageMapper.getPackageNum(pd);
        List<Map<String, Object>> result = packageMapper.getPackage(pd);
        map.put("count", m);
        map.put("list", result);
        return map;
    }

    public int Update(PageData pd) {
        int result = packageMapper.Update(pd);
        return result;
    }

    public String DeletePackage(PageData pd) {
        String id = packageMapper.getQymdmcId(pd);
        pd.put("id", id);
        int result1 = packageMapper.DeletePackage(pd);
        int result2 = packageMapper.DeleteQymc1(pd);
        if (result1 > 0 && result2 > 0) {
            return "删除成功";
        }
        return "删除失败";
    }

    public List<Map<String, Object>> getExcel(PageData pd) {
        List<Map<String, Object>> result = packageMapper.getExcel(pd);
        return result;
    }

    @Override
    public List<Map<String, Object>> getPackageDetails(PageData pd) {
        List<Map<String, Object>> result = packageMapper.getPackageDetails(pd);
        for (int i = 0; i < result.size(); i++) {
            if (StringUtils.isEmpty(result.get(i).get("industryco_d")) && StringUtils.isEmpty(result.get(i).get("esdate"))) {
                result.get(i).put("industryco_d", "-");
                result.get(i).put("esdate", "-");
            }
        }
        return result;
    }

    public int DeleteQymc(PageData pd) {
        int result = packageMapper.DeleteQymc(pd);
        return result;
    }

    @Override
    public int getCountEnterprise(PageData pd) {
        int num = packageMapper.getCountEnterprise(pd);
        return num;
    }

    @Override
    public void updatePackage(PageData pd) {
        packageMapper.updatePackage(pd);
    }

    //企业包中添加企业
//    @Override
//    public int addQymdmcId(PageData pd, List<EntcolDTO> entcolDTO) {
//        String id = packageMapper.getQymdmcId(pd);
//        int sum = packageMapper.addQymdmcId(pd, entcolDTO, id);
//        return sum;
//    }

    @Override
    public int addQymdmcId2(aa aa) {
        String qymdmc = aa.getQymdmc();
        String user = aa.getUser();
        EntcolDTO[] option = aa.getOption();
        String id = packageMapper.getQymdmcId2(qymdmc, user);
        if (StringUtils.isEmpty(id)) {
            return 0;
        }
        int result = packageMapper.addQymdmcId2(option, id);
        return result;
    }

    @Override
    public int getQynum(PageData pd) {

        return packageMapper.getQynum(pd);
    }


    public void close() {
        try {
            this.conn.close();
            this.stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}
